package com.tian.service.impl;

import com.tian.common.CommonResult;
import com.tian.dto.StationGunCommunicateLogQueryReqDto;
import com.tian.entity.StationGunCommunicateLog;
import com.tian.service.StationGunCommunicateLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import plus.ojbk.influxdb.core.InfluxdbTemplate;
import plus.ojbk.influxdb.core.Op;
import plus.ojbk.influxdb.core.Query;
import plus.ojbk.influxdb.core.enums.Order;
import plus.ojbk.influxdb.core.model.QueryModel;
import plus.ojbk.influxdb.util.InfluxdbUtils;

import javax.annotation.Resource;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * {@code @description:} TODO
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-08-23 22:39
 * {@code @version:} 1.0
 */
@Slf4j
@Service
public class StationGunCommunicateLogServiceImpl implements StationGunCommunicateLogService {

    @Resource
    private InfluxdbTemplate influxDBTemplate;

    @Override
    public CommonResult<List<StationGunCommunicateLog>> getStationGunCommunicateLogList(StationGunCommunicateLogQueryReqDto stationGunCommunicateLogQueryReqDto) {
        String sql = "SELECT COUNT(gun_no) FROM " + InfluxdbUtils.getMeasurement(StationGunCommunicateLog.class) +
                " WHERE gun_no='" + stationGunCommunicateLogQueryReqDto.getGunNo() +
                "' AND time > '" + stationGunCommunicateLogQueryReqDto.getStartLogTime().atZone(ZoneId.of("UTC")).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME) +
                "' AND time < '" + stationGunCommunicateLogQueryReqDto.getEndLogTime().atZone(ZoneId.of("UTC")).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME) + "'";
        long count = influxDBTemplate.count(sql);
        log.info("查询到{}条数据", count);
        if (count == 0) {
            return CommonResult.failed("没有查询到数据");
        }
        QueryModel queryModel = new QueryModel();
        Map<String, Object> map = new TreeMap<>();
        map.put("gun_no", stationGunCommunicateLogQueryReqDto.getGunNo());
        queryModel.setMeasurement(InfluxdbUtils.getMeasurement(StationGunCommunicateLog.class));
        queryModel.setMap(map);
        queryModel.setStart(stationGunCommunicateLogQueryReqDto.getStartLogTime());
        queryModel.setEnd(stationGunCommunicateLogQueryReqDto.getEndLogTime());
        queryModel.setOrder(Order.DESC);
        queryModel.setCurrent(stationGunCommunicateLogQueryReqDto.getCurrentPage());
        queryModel.setSize(stationGunCommunicateLogQueryReqDto.getPageSize());
        queryModel.setWhere(Op.where(queryModel));
        List<StationGunCommunicateLog> chargingDataList = influxDBTemplate.selectList(Query.build(queryModel), StationGunCommunicateLog.class);
        return CommonResult.success(chargingDataList);
    }
}
